package vn.com.vega.chacha.v2.Asynctask;

import java.lang.ref.WeakReference;
import java.util.List;

import vn.com.vega.chacha.v2.ActivityBase;
import vn.com.vega.music.clientserver.JsonPlaylist;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.objects.Playlist;

import android.os.AsyncTask;

public class LoadPlaylistCreateByUser extends
		AsyncTask<Void, Void, Void> {

	private WeakReference<ActivityBase> baseActivityRfc;
	private LoadUserPlaylistListener listener;
	private List<Playlist> result = null;
	
	public LoadPlaylistCreateByUser (ActivityBase act, LoadUserPlaylistListener loadListener) {
		baseActivityRfc = new WeakReference<ActivityBase>(act);
		listener = loadListener;
	}
	
	private boolean checkIsLive() {
		ActivityBase actBase = baseActivityRfc.get();
		if (actBase == null || actBase.isDestroy) {
			return false;
		} 
		return true;
	}

	@Override
	protected Void doInBackground(Void... params) {
		// TODO Auto-generated method stub
		try {
//			DataStore dataStore = DataStore.getInstance();
//			result = dataStore.getUserCreatedPlaylistList();
			JsonPlaylist jsonPlaylist = JsonPlaylist.loadPersonalPlaylist();
			if (jsonPlaylist.isSuccess()) {
				result = jsonPlaylist.playlists;
			} else {
				result = null;
			}
		} catch (Exception e) {
			// TODO: handle exception
			result = null;
		}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(Void result) {
		// TODO Auto-generated method stub
		if (isCancelled() || !checkIsLive()) {
			return;
		}
		if (listener != null) {
			listener.finishLoadPlaylist();
		}
		if (this.result != null) {
			listener.loadPlaylistSuccess(this.result);
		} else {
			listener.loadPlaylistError(null);
		}
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		if (!checkIsLive()) {
			return;
		}
		if (listener != null) {
			listener.startLoadPlaylist();
		}
	}
	
	public interface LoadUserPlaylistListener{
		public void startLoadPlaylist();
		public void finishLoadPlaylist();
		public void loadPlaylistError(String errorMessage);
		public void loadPlaylistSuccess(List<Playlist> listUserCreatePlaylist);
	}

}
